#!/usr/local/bin/python
# coding: utf-8
import md5
import urllib
import re
import wsgiref.handlers
import logging

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext import db
from google.appengine.api import images

from Img import Img
import utils.imageutils as imageutils
from Img import NotSupportedImageEncodingError

import logging

heads = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT)'}
         
class tianya(webapp.RequestHandler):
    def get(self):
        try:
            if self.request.path_qs == '/tianya':
                self.redirect('/tianya/')
                return
            self.response.headers['Content-Type'] = 'text/html; charset=gb2312'
            url = self.request.path_qs[len('/tianya/'):]
            if not url:
                self.response.out.write(u"""
                填入天涯帖子的网址，只看楼主:<br/>
                <input id="url" type="text" size="100" name="url"><br/>
                <input type="button" value="go!" onclick="window.location='/tianya/'+document.getElementById('url').value"><br/>
                """.encode('gb2312'))
                return
                
                
            url = urllib.unquote_plus(url)
            
            self.getAuthor(url)
            
            
            l = re.findall('<div id="pContentDiv">(.*)<span id="responsebanner">', self.html, re.M|re.DOTALL)
            if not l:
                raise Exception('Error while handling [%s]'%url)
            else:
                self.output_head()
                self.output_page_index()
                s = l[0]
                spltr = u'<TABLE cellspacing=0 border=0 bgcolor=f5f9fa width=100% ><TR><TD WIDTH=100 ALIGN=RIGHT VALIGN=bottom></TD><TD><font size=-1 color=green><br><center>作者：<a href="/browse/Listwriter.asp?'.encode('gb2312')
                sl = len(spltr)
                
                i=0
                ignore = (self.author != self.pfauthor)
                ni = s.find(spltr,i+sl)
                while ni>=0:
                    logging.error(ignore)
                    if not ignore:
                        self.response.out.write(s[i:ni])
                    i = ni
                    ni = s.find(spltr,i+sl)
                    if ni>0:
                        t = s[i:s.find('</table>', i)]
                        a = re.findall(r'<a href="/browse/Listwriter.asp.*?>(.*?)</a>', t, re.M|re.DOTALL)
                        #self.response.out.write(a)
                        if not a:
                            ignore = True
                        elif a[0] != self.author:
                            ignore = True
                        else:
                            ignore = False
            self.output_page_index()
            self.output_tail()
        except Exception,e:
            #raise e
            self.error(500)
            self.response.out.write('yamede, Server Internal Error')
            
    def getAuthor(self, url):
        """ Get the author of url,
        Return None if failed.
        Return the author name and url's content if succeed.
        """
        #split url
        try:
            l = url.split('/')
            self.id = l[-1].split('.')[0]
            l[-1] = '%s.' + l[-1].split('.')[-1]
            self.t = '/'.join(l)
        except Exception,e:
            raise Exception('Invalid tinaya url')
        
        resp = urlfetch.fetch(url,
               method=urlfetch.GET,
               headers=heads)
        
        if resp.status_code != 200:
            #fetch error
            raise Exception('Cann\'t fetch url [%s]'%url)
        else:
            self.html = resp.content
            self.pfauthor = self.get_page_first_author(self.html)
            
            #get all page ids
            l = re.findall(r"<input type='hidden' name='idArticleslist' value='(.*?)'>", self.html, re.M|re.DOTALL)
            if not l:
                #no idArticleslist, only one page
                #raise Exception('Cann\'t find idArticleslist in [%s]'%url)
                self.ids = [self.id]
            else:
                #the page ids
                self.ids = l[0].split(',')
            
            l = re.findall(u'<table border=0><tr><td  id="pageDivTop">.*?首页'.encode('gb2312'), self.html, re.M|re.DOTALL)
            if l:
                #this page is not the first page, find the first page's url
                
                resp = urlfetch.fetch(self.t%self.ids[0],
                       method=urlfetch.GET,
                       headers=heads)
                if resp.status_code != 200:
                    #fetch error
                    raise Exception('Cann\'t fetch url [%s]'%url)
                else:
                    self.author = self.get_page_first_author(resp.content)
            else:
                #this page is the first page
                self.author = self.pfauthor
            
    def get_page_first_author(self, html):
        l = re.findall(r'<TABLE id="firstAuthor".*?</table>',html,re.M|re.DOTALL)
        if not l:
            raise Exception('Cann\'t find firstAuthor')
        else:
            l = re.findall(r'<a.*?>(.*?)</a>',l[0])
            if not l:
                #failed
                raise Exception('Cann\'t find firstAuthor\'s name')
            else:
                return l[0]
    def output_head(self):
        self.response.out.write('<html><title>powered by appengine</title><body>')
        
    def output_page_index(self):
        #output page index
        l = []
        for index, i in enumerate(self.ids):
            if i == self.id:
                l.append('%d' % (index+1))
                self.last_id = self.ids[max(index-1,0)]
                self.next_id = self.ids[min(index+1,len(self.ids)-1)]
            elif i:
                l.append('<a href="/tianya/%s">%d</a>' % (self.t%i,index+1))
        if self.last_id != self.id:
            self.response.out.write(u'<a href="/tianya/%s">上一页</a>'.encode('gb2312') % (self.t%self.last_id))
        self.response.out.write('&nbsp;&nbsp;&nbsp;')
        if self.next_id != self.id:
            self.response.out.write(u'<a href="/tianya/%s">下一页</a>'.encode('gb2312') % (self.t%self.next_id))
        self.response.out.write('<br/>')
        self.response.out.write('\n'.join(l))
        self.response.out.write('<br/>')
        
    def output_tail(self):
        self.response.out.write('</body></html>')
    
class tianya_slash(webapp.RequestHandler):
    def get(self):
        self.redirect('/tianya/')
        
def main():
    application = webapp.WSGIApplication(
                           [('/tianya/.*', tianya),
                            ('/tianya', tianya),
                           ],
                           debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()
